package demo4;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Scanner;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 石方旭
 * Date: 2022-08-08
 * Time: 17:58
 */
public class TestDemo{

    public static void main(String[] args) {
        System.out.println("请输入你要扫描的目录");
        Scanner scan = new Scanner(System.in);
        String root = scan.next();
        File rootPath = new File(root);
        if(!rootPath.isDirectory()){
            System.out.println("不是目录~~即将退出");
            return;
        }
        if(!rootPath.exists()){
            System.out.println("文件不存在~~即将退出");
            return;
        }
        System.out.println("请输入你要查找的文件名或者文件内容");
        Scanner scan1 = new Scanner(System.in);
        String toFind = scan1.next();
        scanDir(rootPath,toFind);
    }

    public static void scanDir(File root,String toFind){
        File[] files = root.listFiles();
        if(files==null||files.length==0) return;

        for(File f : files){
            if(f.isDirectory()){
                scanDir(f,toFind);
            }else {
                tryToFind(f,toFind);
            }
        }
    }

    public static void tryToFind(File f,String toFind){
        if(f.getName().contains(toFind)){
            try {
                System.out.println("找到文件名相同: 文件路径--->" + f.getCanonicalPath());
            } catch (IOException e) {
                e.printStackTrace();
            }
            return;
        }
        //也可能是文件内容相同,我们要读取file对象的内容在与toFind进行比较
        try(InputStream inputStream = new FileInputStream(f)){
            StringBuilder res = new StringBuilder();
            Scanner scanner = new Scanner(inputStream);
            while(scanner.hasNext()){
                res.append(scanner.nextLine());
            }
            if(res.indexOf(toFind)>=0){
                System.out.println("找到与文件内容相同 文件路径--->" + f.getCanonicalPath());
                return;
            }
        }catch(IOException e){
            e.printStackTrace();
        }
    }
}
